package com.proton.carepatchtemp.fragment;


import android.bluetooth.BluetoothAdapter;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Paint;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.content.ContextCompat;
import android.support.v4.view.animation.LinearOutSlowInInterpolator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Toast;

import com.apkfuns.logutils.LogUtils;
import com.proton.carepatchtemp.R;
import com.proton.carepatchtemp.adapter.DeviceAdapter;
import com.proton.carepatchtemp.application.VCare;
import com.proton.carepatchtemp.base.BaseFragment;
import com.proton.carepatchtemp.constant.Codes;
import com.proton.carepatchtemp.constant.Settings;
import com.proton.carepatchtemp.ui.WaveView;
import com.proton.carepatchtemp.utils.ThreadUtils;
import com.proton.carepatchtemp.utils.ble.BlueDataProvider;
import com.proton.carepatchtemp.utils.ble.BlueUtils;
import com.proton.carepatchtemp.utils.eventbus.MainEvent;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.List;

import static android.content.ContentValues.TAG;


/**
 * A simple {@link Fragment} subclass.
 */
public class SearchDevicesFragment extends BaseFragment {

    private static final int REQUEST_CODE_REQUEST_PERMISSION = 1;
    private static int REQUEST_ENABLE_BT = 1;
    //创建单例
    private static volatile SearchDevicesFragment sInst = null;  // <<< 这里添加了 volatile
    // TODO: 2016/10/31 读取Device Config SP
    public List deviceList = new ArrayList();
    BluetoothAdapter mBluetoothAdapter;
    ImageView imgSearch;
    RecyclerView rView;
    WaveView wave;
    private boolean mScanning;
    private Handler mHandler;
    private DeviceAdapter mDeviceAdapter;
    private LinearLayout mLnlSearchTips;

    public SearchDevicesFragment() {
        //Required empty public constructor
    }

    public static SearchDevicesFragment getSearchDevicesFragmentInstance() {
        Bundle args = new Bundle();
        SearchDevicesFragment inst = sInst;  // <<< 在这里创建临时变量
        if (inst == null) {
            synchronized (SearchDevicesFragment.class) {
                inst = sInst;
                if (inst == null) {
                    inst = new SearchDevicesFragment();
                    sInst = inst;
                }
            }
        }
        inst.setArguments(args);
        return inst;  // <<< 注意这里返回的是临时变量
    }

    @Override
    public void dealEvent(MainEvent event) {
        switch (event.getId()) {

//            case Codes.GET_DEVICE_INFO_FROM_RV:
//                Device device= (Device) event.getObj();
//                if(mScanning){
//                    scanLeDevice(false);
//                }
////                if(mBLE.connect(device.getBtaddress())){
//                    DeviceCenter.add(device);
//                    EventBus.getDefault().post(new MainEvent(Codes.WHEN_CONNECT_DEVICE_TEMP_DATA,device.getBtaddress()));
////                }
//                break;

            case Codes.ECG_BATTERY_ENOUGH:
                if (event.isSuccess()) {
                    VCare.get().setOnceComplete(false);
                    // TODO: 2016/10/31 再次测量需要设置
                    LogUtils.e("return ECG_BATTERY_ENOUGH is success");
                }
                break;
            case Codes.WHEN_GET_DEVICE_ECG_DATA:
                if (VCare.get().isOnceComplete()) {
                    BlueDataProvider.ecgDataed.clear();
                    return;
                }
                if (null != event.getObj() && event.getObj() instanceof byte[]) {
                    byte[] values = (byte[]) event.getObj();
                    //LogUtils.e(values.length);
                    final String data$2 = BlueUtils.getDataString(values);
                    if (!TextUtils.isEmpty(data$2)) {
                        ThreadUtils.runOnOtherThread(() -> {
                            BlueDataProvider.ecgSourceData.addAll(BlueUtils.getEcgData(data$2));
                            LogUtils.e(BlueDataProvider.ecgSourceData);
                            BlueDataProvider.deallAllEcgSourceData();
                        });
                    }
                }
                break;
            case Codes.BT_SCAN_A_DVC:
                if (!deviceList.contains(event.getObj())) {
                    deviceList.add(event.getObj());
                    mDeviceAdapter.notifyDataSetChanged();
                    mLnlSearchTips.setVisibility(View.INVISIBLE);
                }
                break;
            default:
                break;
        }

    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //getPermissins();
        mHandler = new Handler();
        mDeviceAdapter = new DeviceAdapter(deviceList, getContext());
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View rootView = inflater.inflate(R.layout.fragment_search_devices, container, false);
        bindViews(rootView);
        onClicks();
        rView.setLayoutManager(new LinearLayoutManager(getContext()));
        rView.setAdapter(mDeviceAdapter);
        initView(rootView);
        return rootView;
    }

    //
    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (null != mLnlSearchTips && !hidden) {
            deviceList.clear();
            mDeviceAdapter.notifyDataSetChanged();
            mLnlSearchTips.setVisibility(View.VISIBLE);
        }
    }

    public void onClicks() {
        imgSearch.setOnClickListener(view -> {
//            TastyUtils.makeTextShort("点击搜索按钮", TastyToast.SUCCESS);
            imgSearch.setEnabled(false);
            deviceList.clear();
            mDeviceAdapter.notifyDataSetChanged();
            mLnlSearchTips.setVisibility(View.VISIBLE);
            onSearch();
//            TastyUtils.makeTextShort("开始搜索按钮", TastyToast.SUCCESS);
        });
    }

    public void bindViews(View rootView) {
        imgSearch = rootView.findViewById(R.id.search_image);
        rView = rootView.findViewById(R.id.rcv_find_devices);
        wave = rootView.findViewById(R.id.wave);
    }

    public void onSearch() {
//        initBluetooth();
        scanLeDevice(true);
    }

    public void initBluetooth() {
        mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        //是否支持蓝牙
        if (mBluetoothAdapter == null) {
            Toast.makeText(VCare.get(), R.string.ble_not_supported, Toast.LENGTH_LONG).show();
            LogUtils.e(R.string.ble_not_supported);
        }
        //蓝牙是否运作，为否的话进行请求
        if (!mBluetoothAdapter.isEnabled()) {
            Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
            startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
        }
        mBluetoothAdapter.enable();
    }


    private void scanLeDevice(final boolean enable) {
        if (enable) {
            // Stops scanning after a pre-defined scan period.
            mHandler.postDelayed(() -> {
                mScanning = false;
                stopWave(wave);
                imgSearch.setEnabled(true);
            }, Settings.SEARCH_TIME);
            startWave(wave);
            mScanning = true;
            LogUtils.e("post Start Scan!");
            EventBus.getDefault().post(new MainEvent(Codes.BT_START_SEARCH_DEVICE));
        } else {
            mScanning = false;
            stopWave(wave);
        }
    }


    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        if (requestCode == REQUEST_CODE_REQUEST_PERMISSION) {
            if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                Log.e(TAG, "获取" + permissions.toString() + "成功");
            } else {
                Log.e(TAG, "获取" + permissions.toString() + "失败");
            }
        }
    }


    @Override
    public void onEventMainThread(MainEvent event) {
        dealOnEvent(event);
    }

    @Override
    public void onPause() {
        super.onPause();
        if (mScanning) {
            scanLeDevice(false);
        }
    }

    public void startWave(WaveView wave) {
        wave.setDuration(5000);
        wave.setStyle(Paint.Style.FILL);
        wave.setColor(ContextCompat.getColor(getActivity(), R.color.blueCenter));
        wave.setInterpolator(new LinearOutSlowInInterpolator());
        wave.setInitialRadius(120);
        wave.setMaxRadius(336);
        wave.start();
    }

    public void stopWave(WaveView wave) {
        wave.stop();
    }

    private void initView(View rootView) {
        mLnlSearchTips = rootView.findViewById(R.id.lnl_search_tips);
    }
}
